import "../../../../scss/activity/collect/friends_help.scss";
import $ from "jquery";
import "../../../utils/weui";
import moment from "moment";
import Vue from "vue";
import com from "../../../utils/common";
import ReadSection from "../../components/readSection";
import FuncBanner from "../../components/funcbanner";
import CtrlPlay from "../../components/ctrlplay";
import UserJoin from "../../components/userJoin";
import ps from "../../../common/variable";
import wxtool from "../../components/weixin";
import count from "../../../utils/countdown";
import SharePop from "../../components/sharePop";
import viewAddFooter from "../../components/viewAddFooter";
import baseStatus from "../../components/baseActStatus";
import "../../../utils/oldcommon/layer"
import setWxShare from "../../components/setWxShare"
import Scroll from "../../../utils/rankSrcoll";
import NoticePop from "../../components/noticeWay";
let user = wxtool.getWxUserinfo("userinfo");
console.log(user.headimgurl)


$(function () {
  let page = {
    _actid: com.getUrlParam("actid") ? com.getUrlParam("actid") : 1,
    _joinid: com.getUrlParam("joinid") ? com.getUrlParam("joinid") : 1,
    _ispreview: com.getUrlParam("preview") ? com.getUrlParam("preview") : 0,
    _appdata: {
      partinstatusall: ps, // 所有状态
      partinstatus: ps.ParterLook, //当前状态
      countDown: {
        days: "xx",
        hours: "xx",
        minutes: "xx",
        seconds: "xx"
      },
      JoinerMsg: {
        // 已报名用户信息
        Name: "信息",
        RankMsg: 3,
        HelpValue: 0
      },
      RankMsg: [],
    },
    _app: {},
    _init: function () {
      let self = this;
      // 获取活动数据
      com.ajax({
        url: "/act/getstar/getActDetial",
        data: {
          Actid: self._actid,
          Joinid: self._joinid,
          Openid: user.openid,
        },
        ok: function (data) {
          // 需要三个数据,Joinid对应信息, openid对应的用户信息,joinid对应的parters信息
          console.log(data);
          let temp = data["msg"];

          console.log(temp)
          if (temp !== "fail" && typeof temp === "object") {
            if (temp.Catgory == "collect/friends_help") {
              temp.Actid = self._actid;
              temp.Prizes = JSON.parse(temp.Prizes);
              temp.Other = JSON.parse(temp.Other)
              temp.StartDate = moment(temp.StartTime).format("YYYY-MM-DD HH:mm");
              temp.EndDate = moment(temp.EndTime).format("YYYY-MM-DD HH:mm");
              temp.Content = JSON.parse(temp.Content);

              $("#PageTitle").html(temp.Title)
              /*分享信息*/
              let ShareMsg = {};
              ShareMsg.ShareImg = temp.ShareImg;
              ShareMsg.ShareTitle = temp.ShareTitle ? temp.ShareTitle : temp.Title;
              ShareMsg.ShareContent = temp.ShareContent;
              self._appdata.ShareMsg = ShareMsg;

              /* 加载用户信息*/
              if (self._joinid > 1) {
                self._appdata.JoinerMsg.HelpValue = parseInt(data["extra"].Current);
                self._appdata.JoinerMsg.Name = data["extra"].Name;
              }
              /* 加载状态*/
              self._appdata.partinstatus = baseStatus(data);
              let ActStatus = {};
              ActStatus.partinstatusall = ps;
              ActStatus.partinstatus = self._appdata.partinstatus;
              self._appdata.ActStatus = ActStatus;

              /*获取已出多少奖品*/

              com.ajax({
                url: "/act/getSuccessJoiner",
                data: {
                  Actid: self._actid,
                },
                ok: function (data) {
                  console.log(data)
                  if (data["msg"] == "ok") {
                    temp.Prizes.LastNum = data["res"];
                    console.log(temp.Prizes)
                    console.log(temp.Prizes.PrizeNum)
                    if (temp.Prizes.PrizeNum && temp.Prizes.LastNum >= temp.Prizes.PrizeNum) {
                      console.log(temp.Prizes.PrizeNum)
                      temp.Prizes.LastNum = temp.Prizes.PrizeNum;
                      self._appdata.partinstatus = ps.AtActInActiveEnd;
                    }
                    $.extend(self._appdata, temp);
                    self._loadTemp()
                  }
                }
              })
            } else {
              com.alertDialog("类型错误");
            }
          } else {
            com.alertDialog("活动不存在");
          }
        }
      });
    },

    // 根据状态判断数据传输,页面交互
    _analysisStatus: function () {
      let self = this;
      // 用户信息(当打开的是已经有用户报名的链接时)(当是用户打开时)

      if (self._ispreview) {
        $(".preview-footer a:first-child").attr("href", "/dist/activity/collect/friends_help_edit.html?actid=" + self._actid)
        $(".preview-footer a:last-child").attr("href", "/dist/activity/collect/friends_help.html?actid=" + self._actid)
      }
      if (self._joinid > 1) {
        // 检测是否帮忙已经帮忙(是否已经在伙伴里面)
        // 每次用户打开链接都填充分享内容
        let shareData = {
          ShareImg: self._appdata.ShareMsg.ShareImg,
          ShareContent: self._appdata.ShareMsg.ShareContent,
          Actid: self._actid,
        }
        let shareTitle = self._appdata.ShareMsg.ShareTitle;
        let joinerMsg = self._appdata.JoinerMsg;
        console.log(joinerMsg)
        shareData.ShareTitle = joinerMsg.Name + "正在参加" + shareTitle;
        setWxShare.SetShare(shareData)
      }
      else {
        if (!self._ispreview) {
          // 没有人报名时的情况(大概率商家页)
          // 当是商家保存完活动打开页面后
          let checkEditUser = com.getdb(self._actid);
          if (checkEditUser) {
            $(".share_mask").show();
            com.showCenter($(".share_pop"));
            com.savedb(self._actid, false)
          }
          let shareData = {
            ShareTitle: self._appdata.ShareMsg.ShareTitle,
            ShareImg: self._appdata.ShareMsg.ShareImg,
            ShareContent: self._appdata.ShareMsg.ShareContent,
            Actid: self._actid,
          }
          setWxShare.SetShare(shareData)
        }
      }

      // 跳出报名成功弹窗(此时标识用户在自己页面)
      if (self._appdata.partinstatus == self._appdata.partinstatusall.JoinDone) {
        let saveKey = user.openid + self._actid;
        console.log(saveKey)
        let pageActId = com.getdb(saveKey);
        // 当当前用户第一次打开页面时(此时没有存储活动id)
        if (pageActId != self._actid) {
          com.savedb(saveKey, self._actid);
          $('.notice_msg').show()
          com.showCenter($('.sign-suc'));
          // 点击页面自动刷新
          $("#app").on("click", ".sign-suc-footer,.mask", function () {
            $(".mask,.notice_msg,.sign-suc").hide();
            self._takePartInFriendsHelp()
          });
        }
      }
    },
    _checkActStatus: function (act) {
      let self = this;
      let temp = act['msg'];
      let start = moment(temp.StartTime);
      let end = moment(temp.EndTime);
      let now = moment();

      //判断活动是否开始
      if (now.isBefore(start)) {
        return ps.AtActInActiveStart
      }
      //判断活动是否开始
      if (now.isAfter(end)) {
        return ps.AtActInActiveEnd
      }
      // 当用户是参与者进入其他人页面时
      if (act.isJoiner && act.isPageJoin && act.checkPageJoin) {
        return ps.JoinDone
      }
      //判断帮忙者是否参与过活动(帮忙者是参与者)
      if (act.isJoiner && act.isPageJoin && !act.checkPageJoin) {
        return ps.ParterDone
      }
      //判断帮忙者是否参与过活动(帮忙者不是参与者)
      if (act.isJoiner && !act.isPageJoin && !act.checkPageJoin) {
        return ps.ParterLook
      }
      return ps.JoinJustNow
    },
    _analysisData: function (data) {
      for (let i = 0; i < data.length; i++) {
        page._appdata.RankMsg.push({
          "Name": data[i].Name,
          "HelpValue": data[i].Current.toFixed(0),
          "SuccessTime": data[i].UpdateTime,
        })
      }
    },
    _loadTemp: function () {
      let self = this;
      Vue.component("g-section", ReadSection)
      Vue.component("func-banner", FuncBanner);
      Vue.component("music", CtrlPlay);
      Vue.component("user-join", UserJoin);
      Vue.component("share-pop", SharePop);
      Vue.component("notice-pop", NoticePop);
      Vue.component("add-msg", viewAddFooter);

      self._app = new Vue({
        el: "#app",
        data: self._appdata,
        methods: {
          showCenterPops: function (ele) {
            // 显示弹窗,并让其显示在中间
            $(".mask").show();
            ele.show();
            $("body").addClass("index_body");
            let eleHeight = ele.height();
            ele.css("margin-top", -eleHeight / 2 + "px");
          },
          // 提交报名信息
          UserJoinAct: function (data) {
            let JoinData = {};
            JoinData.Actid = self._actid;
            JoinData.Joinid = self._joinid;
            JoinData.ActivityCat = "collect/friends_help";
            JoinData.Results = user.headimgurl;
            JoinData.Name = data["Name"];
            JoinData.Mobile = data["Mobile"];
            JoinData.Other = data["Other"];
            JoinData.Openid = user.openid;
            console.log(data);
            console.log(JoinData);
            com.ajax({
              url: "/act/getstar/joinGetStar",
              method: "post",
              data: JoinData,
              ok: function (data) {
                console.log(data);
                if (data["msg"] == "ok") {
                  self._getJoinByOpenid(1)
                } else if (data["msg"] == "fail") {
                  com.alertDialog("同一活动不能重复报名")
                }
              }
            })
          },
          AlertJoinPop: function () {
            let msg = '<p style="text-align:left;color:#333;">①报名前可先联系商家，确认活动真实性以及记录联系方式哦！<br/>②如发现虚假活动，请在客牛公众号回复我们。</p>';
            layer.open({
              content: msg
              , btn: ['确定', '取消'],
              yes: function () {
                layer.closeAll();
                $('.pop_mask').show();
                com.showCenter($(".pop_user_msg"))
              }
            });
          },
          SendFriend: function () {
            $(".notice_msg").show()
            com.showCenter($('.sign-suc'))
          },
          // 返回自己页面
          BackMine: function () {
            self._getJoinByOpenid(1)
          },
          TakePartIn: function () {
            self._takePartInFriendsHelp();
          },
        },
      })
      self._analysisStatus()

      self._afterTemp();
    },
    _getJoinByOpenid: function (status) {
      let self = this;
      com.ajax({
        url: "/act/getstar/getJoinUserDetail",
        data: {
          Openid: user.openid,
          Actid: self._actid,
        },
        ok: function (dat) {
          console.log(dat);
          let joinMsg = dat["res"];
          console.log(joinMsg);
          if (joinMsg["Id"] > 0) {
            if (status) {
              window.location = "/dist/activity/collect/friends_help.html?actid=" + self._actid + "&joinid=" + joinMsg["Id"];
            }
          } else {
            com.alertDialog("您还未参加活动");
          }

        }
      })
    },
    _afterTemp: function () {
      let self = this;

      // 倒计时
      let countDownTime = setInterval(function () {
        let timeRecord = count.computedTime(moment(self._app.EndDate).format("X"));
        if (timeRecord) {
          self._app.countDown = timeRecord;
        } else {
          self._app.partinstatus = self._app.partinstatusall.AtActInActiveEnd;
          clearInterval(countDownTime)
        }
      }, 1000);
      $("#app").on("click", ".mask,.cancel,.pop_mask,.close,.help-pop", function () {
        $(".mask,.pop_mask,.help-pop").hide();
      })
      $("#app").on("click", ".share_pop,.pop_user_msg,.share-way,.sign-suc", function (event) {
        event.stopPropagation();
      })


      let obj = {
        url: "/act/getstar/getSortList",
        data: {
          PageNum: 20,
          Actid: page._actid,
        },
        callback: self._analysisData
      }
      Scroll.StartScroll(obj)

    },
    _takePartInFriendsHelp: function () {

      let self = this;

      com.ajax({
        url: "/act/getstar/takePartinGetStar",
        data: {
          Openid: user.openid,
          Actid: self._actid,
          Joinid: self._joinid,
          Catgory: "collect/friends_help",
        },
        ok: function (data) {
          console.log(data);
          if (data["msg"] == "ok") {
            self._goldFall();
          } else if (data["msg"] == "success") {
            com.alertDialog("用户助力值已满");
          } else {
            com.alertDialog("您已帮他助力成功了");
          }
        }
      })
    },

    _goldFall: function () {

      let goldFallInterval;
      let goldFallStart = 0;


      let goldFall = {};
      // 生成多个金币
      goldFall.initGoldFall = function () {
        for (let i = 2; i < 4; i++) {
          $('div', '#gold').clone().prependTo('#gold');
        }
      }

      // 开始下降
      goldFall.startGoldFall = function () {
        // 清除金币下降动画
        clearInterval(goldFallInterval);
        goldFall.goldRange();
        goldFallStart = new Date().getTime();
        goldFallInterval = setInterval(goldFall.dropGoldFall, 200);
      }

      //排列
      goldFall.goldRange = function () {
        let num = 1;
        $('div', '#gold').each(function (i) {
          let ww = $(window).width();//窗口宽度
          $(this).css({"margin-left": (-(i + 2) * (ww / 64)) + "px", "left": "50%", "top": "-50px"});//距左距离保持，距上距离变化
          num++;
        });
      }

      // 降落效果
      goldFall.dropGoldFall = function () {
        let now = new Date().getTime();
        if (now - goldFallStart > 3000) {
          clearInterval(goldFallInterval);
          $("#gold").hide();
          $(".help-pop").show()
        }
        let $objs = $('div', '#gold');
        $objs.each(function (i) {
          let wh = $(window).height();
          let selfTop = $(this).offset().top;
          let rnd = Math.round(Math.random() * 100);
          let rnd2 = Math.round(Math.random() * 50);

          //降落的速度
          if (selfTop <= wh)//如果掉到窗口以下
          {
            $(this).css({"top": (selfTop + rnd + rnd2) + "px"});
          }
        });
      }

      // 点击助力
      function fall() {
        // 掉钱的声音
        let audio = document.createElement('audio')  //生成一个audio元素
        audio.src = '/src/music/gold_fall.wav'  //音乐的路径
        document.body.appendChild(audio)  //把它添加到页面中
        audio.play();
        $(".gold-mask,#gold").show();
        goldFall.initGoldFall();
        goldFall.startGoldFall();
      }

      fall()
    },
  }

  page._init()
});